<template>
  <ele-page
    flex-table
    :multi-card="false"
    hide-footer
    style="min-height: 420px"
  >
    <!-- 搜索表单 -->
    <role-search @search="reload" :cache-key="getCurrentInstance().type.name" />
    <ele-card
      :body-style="{ paddingTop: '8px' }"
      flex-table
      :multi-card="false"
    >
      <!-- 表格 -->
      <ele-pro-table
        ref="tableRef"
        row-key="role_id"
        :pagination="pagination"
        :loading="loading"
        flex-table
        :columns="columns"
        :datasource="datasource"
        :show-overflow-tooltip="true"
        v-model:selections="selections"
        :highlight-current-row="true"
        :export-config="{ fileName: '角色数据', datasource: exportSource }"
        :print-config="{ datasource: exportSource }"
        :cache-key="getCurrentInstance().type.name"
      >
        <template #toolbar>
          <el-button
            type="primary"
            class="ele-btn-icon"
            :icon="PlusOutlined"
            @click="openAdd()"
          >
            新建
          </el-button>
          <el-button
            type="danger"
            class="ele-btn-icon"
            :icon="DeleteOutlined"
            @click="remove()"
          >
            删除
          </el-button>
        </template>
        <template #action="{ row }">
          <el-link type="primary" underline="never" @click="openEdit(row)">
            修改
          </el-link>
          <el-divider direction="vertical" />
          <el-link type="primary" underline="never" @click="openAuth(row)">
            分配权限
          </el-link>
          <el-divider direction="vertical" />
          <el-link type="danger" underline="never" @click="remove(row)">
            删除
          </el-link>
        </template>
      </ele-pro-table>
    </ele-card>

    <!-- 新增 -->
    <role-edit action="add" v-model="showAdd" @done="reload" />

    <!-- 修改 -->
    <role-edit
      action="edit"
      :data="current"
      v-model="showEdit"
      @done="reload"
    />
    <!-- 权限分配弹窗 -->
    <role-auth v-model="showAuth" :data="current" />
  </ele-page>
</template>

<script setup>
import { ref, getCurrentInstance } from "vue";
import { ElMessageBox } from "element-plus/es";
import { EleMessage } from "ele-admin-plus/es";
import { PlusOutlined, DeleteOutlined } from "@/components/icons";
import RoleSearch from "./components/role-search.vue";
import RoleEdit from "./components/role-edit.vue";
import RoleAuth from "./components/role-auth.vue";
import { pageRoles, removeRoles, listRoles } from "@/api/system/role";

import { getTypeName } from "@/utils/function";
import { useTable } from "@/hooks/useTable";
import { useOperator } from "@/hooks/operator";
import { useModal } from "@/hooks/useModal";

defineOptions({ name: "SystemRoleTable" });

/** 表格列配置 */
const columns = ref([
  {
    type: "selection",
    columnKey: "selection",
    width: 50,
    align: "center",
    fixed: "left",
  },
  {
    type: "index",
    columnKey: "index",
    width: 50,
    align: "center",
    fixed: "left",
  },
  {
    prop: "role_name",
    label: "角色名称",
    sortable: "custom",
    minWidth: 120,
  },
  {
    prop: "role_code",
    label: "角色标识",
    sortable: "custom",
    minWidth: 120,
  },
  {
    prop: "comments",
    label: "备注",
    sortable: "custom",
    minWidth: 140,
  },
  {
    prop: "created_at",
    label: "创建时间",
    sortable: "custom",
    width: 180,
    align: "center",
  },
  {
    columnKey: "action",
    label: "操作",
    width: 200,
    align: "center",
    slot: "action",
    hideInPrint: true,
    hideInExport: true,
  },
]);

/** 是否显示权限分配弹窗 */
const showAuth = ref(false);

/** 打开权限分配弹窗 */
const openAuth = (row) => {
  current.value = row ?? null;
  showAuth.value = true;
};

/** 删除单个 */
const remove = (row) => {
  const rows = row == null ? selections.value : [row];
  if (!rows.length) {
    EleMessage.error("请至少选择一条数据");
    return;
  }
  ElMessageBox.confirm(
    "确定要删除“" + rows.map((d) => d.role_name).join(", ") + "”吗?",
    "系统提示",
    { type: "warning", draggable: true },
  )
    .then(() => {
      const loading = EleMessage.loading({
        message: "请求中..",
        plain: true,
      });
      removeRoles(rows.map((d) => d.role_id))
        .then((msg) => {
          loading.close();
          EleMessage.success(msg);
          reload();
        })
        .catch((e) => {
          loading.close();
          EleMessage.error(e.message);
        });
    })
    .catch(() => {});
};

/** 导出和打印全部数据的数据源 */
const exportSource = ({ where, orders }) => {
  return listRoles({ ...where, ...orders });
};

const {
  loading,
  pagination,
  tableRef,
  datasource,
  reload,
  current,
  selections,
} = useTable({
  getPages: pageRoles,
  beforeQuery: (params) => {
    // 可以修改或添加查询参数
    console.log("查询参数:", params); // 调试用，实际不需要这一行
    return {
      ...params,
      ...params.where,
    };
  },
  afterQuery: () => {
    // 查询后处理
  },
});

// 使用hook创建各个弹窗
const { visible: showAdd, open: openAdd } = useModal({
  beforeOpen: async () => {
    current.value = null; // 新增时重置数据
    // if (!props.dict_ids) {
    //   throw new Error("请先选择字典");
    // }
  },
});

const { visible: showEdit, open: openEdit } = useModal({
  beforeOpen: async (row) => {
    current.value = row; // 设置当前行数据
    // if (!row?.editable) {
    //   throw new Error("没有编辑权限");
    // }
  },
});
</script>
